"""
配置管理器
负责加载和管理应用程序配置
"""

import os
import ruamel.yaml
from typing import Dict, Any, Optional


class ConfigManager:
    """配置管理器"""
    
    def __init__(self, config_file: str = 'config/robot.yaml'):
        """
        初始化配置管理器
        
        Args:
            config_file: 配置文件路径
        """
        self.config_file = config_file
        self._config = None
        self._load_config()
    
    def _load_config(self):
        """加载配置文件"""
        try:
            yaml = ruamel.yaml.YAML(typ='rt')
            with open(self.config_file, 'r', encoding='utf-8') as file:
                self._config = yaml.load(file)
        except FileNotFoundError:
            print(f"配置文件不存在: {self.config_file}")
            self._config = self._get_default_config()
        except Exception as e:
            print(f"加载配置文件失败: {e}")
            self._config = self._get_default_config()
    
    def _get_default_config(self) -> Dict[str, Any]:
        """获取默认配置"""
        return {
            'robot': {
                'data_source': {
                    'type': os.getenv('DATA_SOURCE_TYPE', 'database'),
                    'csv_file': os.getenv('CSV_FILE', 'data/customer.csv'),
                    'page_size': int(os.getenv('PAGE_SIZE', 10))
                },
                'db': {
                    'host': os.getenv('DB_HOST', 'localhost'),
                    'port': int(os.getenv('DB_PORT', 3306)),
                    'user': os.getenv('DB_USER', 'root'),
                    'pass': os.getenv('DB_PASS', 'root123!'),
                    'dbName': os.getenv('DB_NAME', 'wt_db'),
                    'page': int(os.getenv('DB_PAGE', 0))
                },
                'automation': {
                    'confidence_levels': [0.8, 0.7, 0.6, 0.5],
                    'max_retries': 3,
                    'wait_time': 1,
                    'screenshot_interval': 2
                },
                'app': {
                    'name': '企业微信',
                    'search_shortcut': 'command+space'
                },
                'logging': {
                    'level': 'INFO',
                    'file_path': 'logs/wechat_robot.log',
                    'max_file_size': '10MB',
                    'backup_count': 5,
                    'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    'date_format': '%Y-%m-%d %H:%M:%S'
                }
            }
        }
    
    def get(self, key: str, default: Any = None) -> Any:
        """
        获取配置值
        
        Args:
            key: 配置键，支持点号分隔的嵌套键，如 'robot.db.host'
            default: 默认值
            
        Returns:
            配置值
        """
        keys = key.split('.')
        value = self._config
        
        try:
            for k in keys:
                value = value[k]
            return value
        except (KeyError, TypeError):
            return default
    
    def get_database_config(self) -> Dict[str, Any]:
        """获取数据库配置"""
        return self.get('robot.db', {})

    def get_greeting_config(self) -> Dict[str, Any]:
        """获取问候语配置"""
        return self.get('robot.greeting', {})
    
    def get_automation_config(self) -> Dict[str, Any]:
        """获取自动化配置"""
        return self.get('robot.automation', {})
    
    def get_app_config(self) -> Dict[str, Any]:
        """获取应用配置"""
        return self.get('robot.app', {})
    
    def get_logging_config(self) -> Dict[str, Any]:
        """获取日志配置"""
        return self.get('robot.logging', {})
    
    def get_data_source_config(self) -> Dict[str, Any]:
        """获取数据源配置"""
        return self.get('robot.data_source', {})
    
    def update_config(self, key: str, value: Any):
        """
        更新配置值
        
        Args:
            key: 配置键
            value: 新值
        """
        keys = key.split('.')
        config = self._config
        
        for k in keys[:-1]:
            if k not in config:
                config[k] = {}
            config = config[k]
        
        config[keys[-1]] = value
    
    def save_config(self):
        """保存配置到文件"""
        try:
            yaml = ruamel.yaml.YAML(typ='rt')
            os.makedirs(os.path.dirname(self.config_file), exist_ok=True)
            with open(self.config_file, 'w', encoding='utf-8') as file:
                yaml.dump(self._config, file)
        except Exception as e:
            print(f"保存配置文件失败: {e}")
    
    @property
    def config(self) -> Dict[str, Any]:
        """获取完整配置"""
        return self._config
